<?php


namespace app\api\controller;

use app\api\controller\v1\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use other\SmsMuSend;
use think\console\Input;
use think\Db;
use other\Sms;
use think\Exception;
use think\Queue;
use fast\Http;

//落地页接口
class ZhaoYangPage
{
    const DOUYIN_CALLBACK_TYPE = 1; //抖音
    const TENGXUN_CALLBACK_TYPE = 2; //腾讯
    const BAIDU_CALLBACK_TYPE = 3; //百度
    const UC_CALLBACK_TYPE = 4; //UC

    public function __construct() {
        header("Access-Control-Allow-Origin: *");// 跨域访问
        header("Access-Control-Allow-Headers: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        header("Access-Control-Max-Age:86400");
    }

    //提交表单
    public function post()
    {

        $post = \input('post.');
        $get = !empty($post['param']) ? $post['param'] : []; //页面url地址参数
        $api_params = !empty($post['api_params']) ? $post['api_params'] : []; //第三方自动填充url参数

        $params=$post;

        if (empty($post['name'])) {
            return $this->error('姓名不能为空');
        }
        if (empty($post['mobile'])) {
            return $this->error('手机号不能为空');
        }
        if (empty($post['address'])) {
            return $this->error('城市不能为空');
        }
        if (empty($post['code'])) {
            return $this->error('验证码不能为空');
        }
        /*if (empty($post['money'])) {
            return $this->error('贷款金额必选');
        }*/

        if (empty($get['page_id'])) { //落地页ID
            return $this->error('页面数据有误');
        }
        $landingpage_info = \db('page')->where('page_id', $get['page_id'])->find();
        if (empty($landingpage_info)) {
            return $this->error('落地页有误');
        }
        if ($landingpage_info['landingpage_type'] != 2) {
            return $this->error('落地页类型有误');
        }

        $insertLog = [
            'api_url' => '自研落地页',
            'adv_id' => isset($params['adv_id']) ? $params['adv_id'] : '',
            'phone' => isset($params['mobile']) ? $params['mobile'] : '',
            'name' => isset($params['name']) ? $params['name'] : '',
            'city' => isset($params['address']) ? $params['address'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        $account = \db('account')->where('id', $landingpage_info['acc_id'])->find(); // 投放账号信息

        if(empty($account) ){
            $apiId=Db::name('clue_api_log')->insertGetId($insertLog);
            return $this->error('投放账号不存在');
        }else{
            $insertLog['adv_id']=$account['adv_id'];
            $apiId=Db::name('clue_api_log')->insertGetId($insertLog);
            if($account['status'] == 2){
                return $this->error('投放账号已被停用');
            }
        }


//        writelog(json_encode($post,JSON_UNESCAPED_UNICODE));
//        writelog(json_encode(\input('param.'),JSON_UNESCAPED_UNICODE));
        $addrCity=$post['address'];
        $post['address']=[$post['address']];

//        // 测试数据
//         $post = [
//            'name' => "测试",
//            'money' => '5-10万',
//            'address' =>['广州'],
//            'che' => "111",
//            'carBuyMethod' => "全款车",
//            'carLimit' => "小于三年",
//            'mobile' => 15999999999,
//            'code' => 1111,
//        ];
//        $get = $api_params = [];
//        $get['page_id'] = '1802811731321868';

        $captcha = $post['code'] ?? ''; // 验证码
        $mobile = $post['mobile'] ?? ''; // 手机号码

        $channel_type = $landingpage_info['channel_type']; // 渠道媒体:1=巨量,2=腾讯,3=百度

//        if ($landingpage_info['id'] != 77) {
            //短信验证码验证
            $event = 'form_post'; //表单提交
            $perfix = '86';
            $check = Sms::check($mobile, $perfix, $captcha, $event);
            if ($check === false) {
                return $this->error('验证码错误');
            }
//        }

        //撞库判断 同一手机同一账号一个月内不能重复提交
        $exist = \db('clue')
            ->where('phone', $mobile)
            ->where('adv_id', $account['adv_id'])
            ->whereTime('create_time', 'between', [strtotime("-1 month"), time()])
            ->find();
        if (!empty($exist)) {
            return $this->error('请勿重复提交');
        }

        $address = $post['address'] ?? ""; //所在城市
        // 所在城市 数据
        $city_info = clue_city_transform($address);
        if (empty($city_info)) {
            return $this->error('所在城市数据查询有误');
        }
        $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
        $city = $province['id'] . '-' . $city_info['id'];

        //城市是否禁用
        $isCity = model('accountCity')->where(['acc_id' => $account['id'], 'city' => $city, 'status' => 1])->find();
        if (!empty($isCity)) {
            return $this->error('账户城市已禁用');
        }

        // 城市是否准入
        $is_allow = (new \app\common\model\Clue())->allowAccountCity($account['id'], $city);
        if ($is_allow === false) {
            return $this->error('非需求城市');
        }

        //加单机锁5s
        $redis = redis();
        $lock_key = config('config.prefix') . "landingpage_accept_clue_phone_" . $mobile;
        if ($redis->get($lock_key)) {
            return $this->error('线索手机重复请求');
        }
        $redis->setex($lock_key, 5, 1);

        $time = time();
        $ip = request()->ip();
        $form_id = \db('landingpage_post')->insertGetId([
            'page_id' => $landingpage_info['id'],
            'mobile' => $mobile,
            'ip' => $ip,
            'create_time' => $time,
            'update_time' => $time,
            'get_data' => json_encode(array_merge($get, $api_params), JSON_UNESCAPED_UNICODE),
            'post_data' => json_encode($post, JSON_UNESCAPED_UNICODE),
            'is_callback' => 0, //是否转化请求成功
        ]);
        if (!$form_id) {
            $redis->del($lock_key); // 解锁
            return $this->error('提交表单失败');
        }

//        if ($landingpage_info['id'] != 77) { // 测试落地页
            // 媒体转化回传api
            $callback_ref = false;
            if ($channel_type == self::BAIDU_CALLBACK_TYPE) { // 百度
                if (empty($api_params['bd_vid'])) {
                    $redis->del($lock_key); // 解锁
                    return $this->error('百度bd_vid参数有误');
                }
                if (empty($account['ocpc_token'])) {
                    $redis->del($lock_key); // 解锁
                    return $this->error('账号ocpc_token参数不存在，请联系客服');
                }
                $callback_ref = $this->baiduCallbackApi($form_id, $api_params['bd_vid'], $account['ocpc_token'], $landingpage_info['id']); //转化回转api
            } elseif ($channel_type == self::TENGXUN_CALLBACK_TYPE) { // 腾讯
                if (empty($get['qz_gdt']) && empty($get['gdt_vid'])) {
                    $redis->del($lock_key); // 解锁
                    return $this->error('腾讯回传参数有误');
                }
                $click_id = !empty($get['gdt_vid']) ? $get['gdt_vid'] : $get['qz_gdt'];
                $callback_ref = $this->tengxunCallbackApi($form_id, $landingpage_info['online_url'], $click_id); //转化回转api
            } elseif ($channel_type == self::DOUYIN_CALLBACK_TYPE) { // 抖音

                if (empty($api_params['clickid'])) {
                    $redis->del($lock_key); // 解锁
                    return $this->error('回传授权失败，请在头条或抖音中打开链接');
                }
                $callback_ref = $this->douyinCallbackApi($form_id, $get['clickid']); //转化回转api
            } elseif ($channel_type == self::UC_CALLBACK_TYPE) { // UC
                if (empty($api_params['domain'])) {
                    $redis->del($lock_key); // 解锁
                    return $this->error('UC回传参数有误');
                }
                $domain_url = str_replace('&amp;', '&', $api_params['domain']); // 转义字符&
                $callback_ref = $this->ucCallbackApi($form_id, $domain_url); //转化回转api
            }
            if ($callback_ref === false) {
                $redis->del($lock_key); // 解锁
                return $this->error('转化回传失败');
            }
//        }

        //车贷 表单参数
        $name = $post['name'] ?? ""; //姓名
        $money = $post['money'] ?? "10万"; //贷款金额
        $pro_id = $landingpage_info['pro_id'];

        //产品
        $car_arr = $house_arr=$public_funds_arr=$company_arr = [];
        $house = $car =$company=$public_funds= "";
        $remark_arr = [];
        $remark = [];
        if (!empty($money)) {
            $remark_arr['贷款金额'] = $money;
        }
//        if ($pro_id == 3) { // 房抵
//            if (!empty($post['house_buy_method'])) {
//                $remark_arr['房屋情况'] = $post['house_buy_method'];
//                $house_arr[] = "房屋情况:".$post['house_buy_method']; //房屋情况
//            }
//            if (!empty($post['house_type'])) {
//                $remark_arr['房屋类型'] = $post['house_type'];
//                $house_arr[] = "房屋类型:".$post['house_type']; //车辆购买方式
//            }
//
//            //组 字段 车辆信息 house
//            if (!empty($house_arr)) {
//                $house = implode(" | ", $house_arr);
//            }
//            //组 字段 remark
//            $remark = $remark_arr;
//
//        } elseif ($pro_id == 4) { // 车抵
//            if (!empty($post['che'])) {
//                $remark_arr['车辆型号'] = $post['che'];
//                $car_arr[] = "车辆型号:".$post['che']; //车辆型号
//            }
//            if (!empty($post['carBuyMethod'])) {
//                $remark_arr['车辆购买方式'] = $post['carBuyMethod'];
//                $car_arr[] = "车辆购买方式:".$post['carBuyMethod']; //车辆购买方式
//            }
//            if (!empty($post['carLimit'])) {
//                $remark_arr['车辆年限'] = $post['carLimit'];
//                $car_arr[] = "车辆年限:".$post['carLimit']; //车辆年限
//            }
//            if (!empty($post['carType'])) {
//                $remark_arr['车辆状态'] = $post['carType'];
//                $car_arr[] = "车辆状态:".$post['carType']; //车辆状态
//            }
//            if (!empty($post['carModel'])) {
//                $remark_arr['车辆品牌'] = $post['carModel'];
//                $car_arr[] = "车辆品牌:".$post['carModel']; //车辆品牌
//            }
//            //组 字段 车辆信息 car
//            if (!empty($car_arr)) {
//                $car = implode(" | ", $car_arr);
//            }
//            //组 字段 remark
//            $remark = $remark_arr;
//        }elseif ($pro_id==6){
//            $public_funds_arr[]=$post['public_funds'];
//            $public_funds=$post['public_funds'];
//            $remark[]=$post['public_funds'];
//        }elseif ($pro_id==7){
//            $company_arr[]=$post['company'];
//            $company=$post['company'];
//            $remark[]=$post['company'];
//
//        }else{
            if(!empty($post['car'])){
                $car=$post['car'];
                $remark[]=$post['car'];
            }
            if(!empty($post['house'])){
                $house=$post['house'];
                $remark[]=$post['house'];
            }
            if(!empty($post['public_funds'])){
                $public_funds=$post['public_funds'];
                $remark[]=$post['public_funds'];
                if(!empty($post['company_type'])){
                    $public_funds.=','.$post['company_type'];
                    $remark[]=$post['company_type'];
                }
            }
            if(!empty($post['company'])){
                $company=$post['company'];
                $remark[]=$post['company'];
            }
//        }
//        if (!empty($remark) && is_array($remark)) {
            $remark = json_encode($remark, JSON_UNESCAPED_UNICODE);
//        }

        // 可选贷款点
//        if (!empty($post['pro_type'])) {
//            $pro_id = 5;
//            $car = $house = $remark = "";
//            if ($post['pro_type'] == "车抵") {
//                $pro_id2 = 4;
//            } elseif ($post['pro_type'] == "房抵") {
//                $pro_id2 = 3;
//            }
//            if (!empty($post['car'])) { // 车
//                $car = $post['car'];
//                $form_array = explode("|", $post['car']);
//            } elseif (!empty($post['house'])) { // 房
//                $house = $post['house'];
//                $form_array = explode("|", $post['house']);
//            }
//            foreach ($form_array as $v) {
//                $detail = explode(":", $v);
//                $remark_array[$detail[0]] = $detail[1];
//            }
//            if (!empty($remark_array)) {
//                $remark = json_encode($remark_array, JSON_UNESCAPED_UNICODE);;
//            }
//        }

        //记录线索成本
        $clueCost = model('ClueAddCost')->where(['account_id' => $account['id'], 'pro_id' => $pro_id, 'city' => $city, 'status' => 1])->find();
        if (empty($clueCost)) {
            // 找不到城市就找默认全国城市
            $clueCost = model('ClueAddCost')->where(['account_id' => $account['id'], 'pro_id' => $pro_id, 'city' => "", 'status' => 1])->find();
        }
        if (!empty($clueCost)) {
            $price = $clueCost['money'];
            $true_price = $clueCost['money'];
            $xz_price = $clueCost['money'];
            $xz_true_price = $clueCost['money'];
            $xz_price2 = $clueCost['money'];
            $xz_true_price2 = $clueCost['money'];
            $xz_price3 = $clueCost['money'];
            $xz_true_price3 = $clueCost['money'];
            $xz_price4 = $clueCost['money'];
            $xz_true_price4 = $clueCost['money'];
        } else {
            $price = $account['clue_cost'];
            $true_price = $account['clue_cost'];
            $xz_price = $account['clue_cost'];
            $xz_true_price = $account['clue_cost'];
            $xz_price2 = $account['clue_cost'];
            $xz_true_price2 = $account['clue_cost'];
            $xz_price3 = $account['clue_cost'];
            $xz_true_price3 = $account['clue_cost'];
            $xz_price4 = $account['clue_cost'];
            $xz_true_price4 = $account['clue_cost'];
        }

        $type = $account['channel_id'] ?? 1; // 对应媒体渠道表channel_id
        // 线索入库
        $clue = [
            'type' => $type, // 1：百度，2：腾讯，3：巨量
            'adv_id' => $account['adv_id'], // 第三方广告账户id
            'clue_id' => create_no('N'), // 自生成线索id
            'pro_id' => $pro_id, // 产品id
            'pro_id2' => $pro_id2 ?? 0, // 可选产品id
            'clue_name' => $name, //姓名
            'phone' => $mobile, //电话
            'city' => $city, //城市
            'apply_limit' => $money, // 贷款申请额度
            'car' => $car, //车辆信息
            'house' => $house, // 房屋信息
            'public_funds' => $public_funds,
            'company' => $company,
            'clue_type' => "",
            'age' => 0,
            'wechat' => "",
            'gender' => 0,
            'email' => "",
            'source' => "",
            'qq' => "",
            'site_url' => "",
            'page_id' => $landingpage_info['page_id'],
            'page_name' => "",
            'campaign_name' => "",
            'adgroup_name' => "",
            'unit_name' => "",
            'creative_name' => "",
            'ad_name' => "",
            'search_term' => "",
            'keyword' => "",
            'clue_local' => "",
            'ip' => $ip,
            'remark' => $remark,
            'create_time' => $time,
            'update_time' => $time,
            'price' => $price ?? 0,
            'true_price' => $true_price ?? 0,
            'account_id' => $account['id'],
            'xz_price' => $xz_price,
            'xz_true_price' => $xz_true_price,
            'xz_price2' => $xz_price2,
            'xz_true_price2' => $xz_true_price2,
            'xz_price3' => $xz_price3,
            'xz_true_price3' => $xz_true_price3,
            'xz_price4' => $xz_price4,
            'xz_true_price4' => $xz_true_price4,
            'promotion_id' => $get['promotionid'] ?? "",
        ];

        Db::startTrans();
        try {
            $clue_id = \db('clue')->insertGetId($clue); // 新增线索数据
            \db('landingpage_post')->where('id', $form_id)->update(['is_callback' => 1, 'clue_id' => $clue_id]); //更新表单记录
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            writelog("线索入库失败".$e->getFile(). $e->getLine(). $e->getMessage(), "insert_clue");
            $redis->del($lock_key); // 解锁
            return $this->error('线索提交失败');
        }

        // 短信测试 不分发线索 todo
//        if ($landingpage_info['id'] == 77) {
//            return $this->success();
//        }
        // 推送线索

        //独立商户直接推给他
        if($landingpage_info['page_id'] == '998818977365' ){
            $merchant_id=0;
            if($addrCity=='武汉'){
                $wuhanS=$redis->get('wuhannum');
                if($wuhanS%2==0){
                    $merchant_id=34;
                }else{
                    $merchant_id=33;
                }
            }else{
                if(in_array($addrCity,['连云港','襄阳','东莞','商丘','佛山','泉州','杭州','南京','大连','长沙'])){
                    $merchant_id=34;
                }
                if(in_array($addrCity,['新乡','平顶山','许昌','济宁'])){
                    $merchant_id=33;
                }
            }

            if(empty($merchant_id)){
                writelog("线索分发失败:城市".$addrCity.'未指定商户', "find_push_error");
                return $this->success('提交成功');
            }
            $pushRes=$this->findPush($clue_id,$merchant_id);
            $pushRes=$pushRes->getData();
//            dump($pushRes);die;
            if($pushRes['code']==0){
                $redis->incr('wuhannum');
                return $this->success('提交成功');
            }else{
                writelog("线索分发失败".$pushRes['message'], "find_push_error");
                return $this->success('提交成功');

            }
        }

        $jobHandlerClassName  = 'app\job\ExprotClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName     = "ExprotClue";
        $jobData = ['id' => $clue_id];
        Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        $redis->del($lock_key); // 解锁
        // 本地运行
        /*$clueModel = new \app\common\model\Clue();
        $clue_info = $clueModel->find($clue_id);
        $clueApi = new \app\api\controller\v1\Clue();
        $clueApi->cluePush($clue_info, true);*/

        return $this->success('提交成功');
    }


    public function findPush($id,$mid){

//            $id = input('post.id');
//            $mid = input('post.merchant');
//            $pid = input('post.mrule');
            $city = input('post.show_city');
            $pushChannel = input('post.push_channel');


            $merchant=Db::name('merchant')->find($mid);
            if(!$merchant){
                return $this->error('商户获取失败');
            }
            $push=Db::name('push')->where(['mer_id'=>$mid,'status'=>1])->find();
            if(!$push){
                return $this->error('分发规则获取失败');
            }
            if($merchant['status']!=1){
                return $this->error('该商户已禁用');
            }

            $success=0;
            $error=0;

                $clue_info = Db::name('clue')->find($id);
                if(!$clue_info){
                    return $this->error('线索获取失败');
                }
                if(strpos($clue_info['clue_name'], '测试') !== false){
                    return $this->error('测试线索不能推送！');
                }
                if(!empty($city)){
                    $clue_info['show_city']=$city;
                }
                if(!empty($pushChannel)){
                    $clue_info['push_channel']=$pushChannel;
                }
                $res=(new ClueModel())->sendMerchantClue($push,$clue_info,1);
                if($res===true){
//                    $this->RecordSystemLog($this->uid,$this->behavior,'线索推送成功,操作ID: '.$id);
                    $sendPhone=$merchant['phone'];
                    if($merchant['is_send_phone']==1&&$sendPhone&&request()->domain()!=config('testdomain')){
                        $mobiles=$sendPhone;
                        $content='【'.config('database')['host_sms_name']."】提醒你有个线索查看！";
                        $extno='';
                        $sendtime='';
//                        MessageSend::send($mobiles,$extno,$content,$sendtime);
                        $sendRes=SmsMuSend::send($mobiles,$content);
                    }

                    //子商户推送
                    if($merchant['is_sub_mer']==1){
                        // 1.当前任务将由哪个类来负责处理。
                        // 当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
                        $jobHandlerClassName  = 'app\job\SubCluePush@fire';
                        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                        $jobQueueName     = "SubCluePush";

                        $jobData = ['mer_id'=>$merchant['id'],'clue_id'=>$clue_info['id']];
                        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
                    }
                    return $this->success('线索推送成功');
                }else{
                    return $this->error('线索推送失败：'.$clue_info['clue_name'].$res);
                }



    }



    // 落地页城市
    public function getCity_bak()
    {
        $data = [
            [
                'province' => "广东",
                'cities' => ['广州', '佛山', '惠州', '深圳',]
            ],
            [
                'province' => "广西",
                'cities' => ['柳州', '南宁', '钦州', '玉林',]
            ],
            [
                'province' => "河北",
                'cities' => ['沧州', '石家庄']
            ],
            [
                'province' => "湖南",
                'cities' => ['郴州', '长沙', '怀化', '株洲',]
            ],
            [
                'province' => "山东",
                'cities' => ['东营', '威海', '烟台', '济南', '青岛']
            ],
            [
                'province' => "北京",
                'cities' => ['北京']
            ],
            [
                'province' => "上海",
                'cities' => ['上海']
            ],
            [
                'province' => "重庆",
                'cities' => ['重庆']
            ],
            [
                'province' => "湖北",
                'cities' => ['武汉', '黄冈', '孝感',]
            ],
            [
                'province' => "四川",
                'cities' => ['成都', '南充', '巴中', '达州']
            ],
            [
                'province' => "浙江",
                'cities' => ['宁波', '温州', '台州', '绍兴', '金华', '嘉兴', '杭州']
            ],
            [
                'province' => "黑龙江",
                'cities' => ['哈尔滨']
            ],
            [
                'province' => "福建",
                'cities' => ['福州']
            ],
            [
                'province' => "江苏",
                'cities' => ['常州', '无锡', '淮安', '苏州', '镇江', '扬州', '盐城', '连云港', '南通']
            ],
            [
                'province' => "河南",
                'cities' => ['许昌', '洛阳']
            ],
            [
                'province' => "云南",
                'cities' => ['昭通']
            ],
            [
                'province' => "安徽",
                'cities' => ['滁州']
            ],
            [
                'province' => "辽宁",
                'cities' => ['沈阳']
            ],
            [
                'province' => "贵州",
                'cities' => ['遵义']
            ],
        ];
        return $this->success('ok', $data);
    }


    public function getProvince()
    {
        $data=[

        ];
    }

    // 落地页城市
//    public function getCity()
//    {
//        $data = [
//            [
//                'province' => "浙江",
//                'cities' => ['温州', '台州', '绍兴', '衢州', '宁波', '丽水', '金华', '嘉兴', '湖州', '杭州']
//            ],
//            [
//                'province' => "云南",
//                'cities' => ['昭通', '曲靖', '昆明']
//            ],
//            [
//                'province' => "四川",
//                'cities' => ['自贡', '资阳', '宜宾', '雅安', '遂宁', '内江', '南充', '绵阳', '眉山', '泸州', '乐山', '广安', '德阳', '达州', '成都', '巴中']
//            ],
//            [
//                'province' => "陕西",
//                'cities' => ['咸阳', '西安']
//            ],
//            [
//                'province' => "山西",
//                'cities' => ['运城', '太原']
//            ],
//            [
//                'province' => "山东",
//                'cities' => ['淄博', '枣庄', '烟台', '潍坊', '威海', '日照', '青岛', '临沂', '聊城', '济宁','济南', '菏泽', '东营', '德州', '滨州']
//            ],
//            [
//                'province' => "宁夏",
//                'cities' => ['银川']
//            ],
//            [
//                'province' => "辽宁",
//                'cities' => ['沈阳', '大连']
//            ],
//            [
//                'province' => "江西",
//                'cities' => ['宜春', '上饶', '南昌']
//            ],
//            [
//                'province' => "江苏",
//                'cities' => ['镇江', '扬州','盐城', '徐州', '无锡', '苏州', '南通', '南京', '连云港',  '淮安', '常州']
//            ],
//            [
//                'province' => "吉林",
//                'cities' => ['长春']
//            ],
//            [
//                'province' => "湖南",
//                'cities' => ['株洲', '长沙', '岳阳', '怀化', '衡阳', '郴州', '常德']
//            ],
//            [
//                'province' => "湖北",
//                'cities' => ['孝感', '襄阳', '武汉', '十堰','荆州', '荆门', '黄石', '黄冈','鄂州']
//            ],
//            [
//                'province' => "黑龙江",
//                'cities' => ['哈尔滨']
//            ],
//            [
//                'province' => "河南",
//                'cities' => ['周口', '郑州', '许昌', '漯河', '洛阳']
//            ],
//            [
//                'province' => "河北",
//                'cities' => ['沧州', '衡水', '廊坊', '唐山', '石家庄']
//            ],
//            [
//                'province' => "贵州",
//                'cities' => ['遵义', '黔东南', '贵阳']
//            ],
//            [
//                'province' => "广西",
//                'cities' => ['柳州', '南宁', '钦州', '玉林', '河池']
//            ],
//            [
//                'province' => "广东",
//                'cities' => ['肇庆', '湛江', '深圳', '汕头','江门', '惠州', '河源', '广州','佛山', '东莞']
//            ],
//            [
//                'province' => "福建",
//                'cities' => ['福州', '龙岩', '泉州']
//            ],
//            [
//                'province' => "天津",
//                'cities' => ['天津']
//            ],
//            [
//                'province' => "北京",
//                'cities' => ['北京']
//            ],
//            [
//                'province' => "上海",
//                'cities' => ['上海']
//            ],
//            [
//                'province' => "重庆",
//                'cities' => ['重庆']
//            ],
//            [
//                'province' => "安徽",
//                'cities' => ['滁州', '芜湖', '马鞍山', '合肥', '阜阳', '蚌埠']
//            ],
//        ];
//        return $this->success('ok', $data);
//    }
    // 获取全国城市
    public function getAllCity()
    {
        $redis = redis();
        $key = config('config.prefix') . "landingpage_all_city";
        $city = $redis->get($key);
        $data = json_decode($city, true);
        //$data = [];
        if (empty($data)) {
            $provinces = \db('city')->where(['pid' => 1, 'type' => 1])->select();// 省份
            $citys = \db('city')->where(['type' => 2])->select();// 城市
            $data = [];
            foreach ($provinces as $k => $province) {
                $data[$k] = ['province' => $province['name']];
                foreach ($citys as $city) {
                    //$data[$k]['cities'][] = "请选择";
                    if ($province['id'] == $city['pid']) {
                        $data[$k]['cities'][] = $city['name'];
                    }
                }
            }
            $redis->set($key, json_encode($data, JSON_UNESCAPED_UNICODE), 86400);
        }

        return $this->success('ok', $data);
    }

    // 落地页 协议内容
    public function getConfig()
    {
        $infos = \db('system_config')->column('extra', "_key");

        $data = [
            'landingpage_text1' => htmlspecialchars_decode($infos['landingpage_text1']),
            'landingpage_text2' => htmlspecialchars_decode($infos['landingpage_text2']),
            'landingpage_text3' => htmlspecialchars_decode($infos['landingpage_text3']),
            'tx_landingpage_text1' => htmlspecialchars_decode($infos['tx_landingpage_text1']),
            'tx_landingpage_text2' => htmlspecialchars_decode($infos['tx_landingpage_text2']),
            'tx_landingpage_text3' => htmlspecialchars_decode($infos['tx_landingpage_text3']),
            'uc_landingpage_text1' => htmlspecialchars_decode($infos['uc_landingpage_text1']),
            'uc_landingpage_text2' => htmlspecialchars_decode($infos['uc_landingpage_text2']),
            'uc_landingpage_text3' => htmlspecialchars_decode($infos['uc_landingpage_text3']),
            'douyin_landingpage_text1' => htmlspecialchars_decode($infos['douyin_landingpage_text1']),
            'douyin_landingpage_text2' => htmlspecialchars_decode($infos['douyin_landingpage_text2']),
            'douyin_landingpage_text3' => htmlspecialchars_decode($infos['douyin_landingpage_text3']),
        ];
        return $this->success('ok', $data);
    }


    //发送验证码
    public function sendMsg()
    {
        $post = \input('post.');

        if (empty($post['page_id'])) {
            return $this->error('缺少落地页参数');
        }

        $landingpage_info = \db('page')->where('page_id', $post['page_id'])->find();
        if (empty($landingpage_info)||$landingpage_info['landingpage_type'] != 2) {
            return $this->error('落地页类型或短信签名有误');
        }

        if (empty($post['mobile'])) {
            return $this->error('手机号码为空');
        }

        if (strlen($post['mobile']) != 11) {
            return $this->error('手机号码格式有误');
        }

        $checknum = preg_match("/^1\d{10}$/", $post['mobile'], $matches);
        if ($checknum == 0) {
            return $this->error('手机号码格式有误');
        }

        $event = "form_post";
        $last = Sms::get($post['mobile'], $event);
        if ($last && time() - $last['createtime'] < 60) {
            return $this->error('发送频繁');
        }
        $ipSendTotal = \db('sms')
            ->where(['ip' => request()->ip()])
            ->whereTime('createtime', '-1 hours')
            ->count();
        if ($ipSendTotal >= 5) {
            return $this->error('发送频繁');
        }

//        $account = Db::name('account')->where('id',$landingpage_info['acc_id'])->find();

        //发送验证码
//        $sendRes = Sms::send($post['mobile'], '86', null, $event, $account['acc_desc']);
        $sendRes = Sms::send($post['mobile'], '86', null, $event, config('database')['host_sms_name']);

        if (empty($sendRes) || $sendRes === false) {
            return $this->error('发送验证码失败');
        }

        return $this->success('验证码已发送，5分钟内有效');
    }


    public function getCity(){
        $pid=input('param.pid');
        $city = \db('city')->field(['id','name'])->where(['pid' => $pid, 'type' => 2])->select();// 省份
        return $this->success('', $city);

    }


    public function getHkCity(){
        $pid=input('param.pid');
//        $city = \db('city')->field(['id','name'])->where(['pid' => $pid, 'type' => 2])->select();// 省份
        $cityData=[
            '16'=>[
                ['id'=>'','name'=>'连云港'],
                ['id'=>'','name'=>'南京'],
            ],
            '14'=>[
                ['id'=>'','name'=>'长沙'],
            ],

            '13'=>[
                ['id'=>'','name'=>'武汉'],
                ['id'=>'','name'=>'襄阳'],
            ],

            '4'=>[
                ['id'=>'','name'=>'泉州'],
            ],
            '11'=>[
                ['id'=>'','name'=>'商丘'],
                ['id'=>'','name'=>'许昌'],
                ['id'=>'','name'=>'平顶山'],
                ['id'=>'','name'=>'新乡'],
            ],
            '6'=>[
                ['id'=>'','name'=>'东莞'],
                ['id'=>'','name'=>'佛山'],
            ],
            '31'=>[
                ['id'=>'','name'=>'杭州'],
            ],
            '18'=>[
                ['id'=>'','name'=>'大连'],
            ],
            '22'=>[
                ['id'=>'','name'=>'济宁'],
            ],
        ];

        return $this->success('', $cityData[$pid]);

    }

    /**
     * 抖音巨量转化回传api对接
     * @params int $form_id 表单id
     * @params string $clickid 抖音巨量回转标识
     * @return boolean
     */
    public function douyinCallbackApi($form_id, $clickid)
    {
        $url = "https://analytics.oceanengine.com/api/v2/conversion";
        $context = [
            'event_type' => "form",
            'context' => [
                'ad' => ['callback' => $clickid]
            ],
            'timestamp' => time(),
        ];
        $req_data = json_encode($context, JSON_UNESCAPED_UNICODE);
        $result = $this->postJson($url, $req_data);
        writelog("表单id：{$form_id}，抖音请求转化回传api,请求参数：{$req_data},返回参数:".$result, 'callbackapi');
        if (empty($result)) {
            writelog("抖音请求转化回传api失败1", 'callbackapi');
            return false;
        }
        $result_arr = json_decode($result, true);
        if (empty($result_arr)) {
            writelog("抖音请求转化回传api失败2", 'callbackapi');
            return false;
        }
        if ($result_arr['code'] != 0) {
            writelog("抖音请求转化回传api失败3:" . $result_arr['message'], 'callbackapi');
            return false;
        }

        return true;
    }

    /**
     * 百度转化回传api对接
     * @params int $form_id 表单id
     * @params string $clickid 百度回转标识
     * @params string $token) 百度回转标识
     * @params int $page_id 落地页主键id
     * @return boolean
     */
    public function baiduCallbackApi($form_id, $bc_vid, $token, $page_id)
    {
        //$token = "k6zi2NV124KbnuZj3666cx1gGnPTR2bQ@ejarcCAzT8y25cBGSc7qxWCyv0fPxp7g";
        $url = "https://ocpc.baidu.com/ocpcapi/api/uploadConvertData";

        $conversionTypes = [
            'logidUrl' => 'http://landingpage.fengzhu.top/?landingpage_id='.$page_id.'&bd_vid='.$bc_vid, // 您的落地页url
            'newType' => 3 // 转化类型请按实际情况填写 表单提交成功
        ];
        $reqData = array('token' => $token, 'conversionTypes' => $conversionTypes);
        $json_req_data = json_encode($reqData, JSON_UNESCAPED_UNICODE);
        $result = $this->postJson($url, $json_req_data);
        writelog("表单id：{$form_id}，百度请求转化回传api,请求参数:{$json_req_data},返回参数:".$result, 'callbackapi');
        if (empty($result)) {
            writelog("百度请求转化回传api失败1", 'callbackapi');
            return false;
        }
        $result_arr = json_decode($result, true);
        if (empty($result_arr)) {
            writelog("百度请求转化回传api失败2", 'callbackapi');
            return false;
        }
        if ($result_arr['header']['status'] != 0) {
            writelog("百度请求转化回传api失败3:" . json_encode($result_arr,JSON_UNESCAPED_UNICODE), 'callbackapi');
            return false;
        }

        return true;
    }

    /**
     * UC转化回传api对接
     * @params int $form_id 表单id
     * @params int $url 前端页面完整url
     * @return boolean
     */
    public function ucCallbackApi($form_id, $form_url)
    {
        $url = "https://huichuan.uc.cn/callback/webapi";

        $params = [
            'link' => $form_url,
            'event_type' => 5, // 转化类型请按实际情况填写 表单提交
            "event_time" => round(microtime(true) * 1000), // 毫秒数
            'source' => "",
            //'outer_event_id' => "",
        ];
        $result = Http::sendRequest($url, $params,'GET');
        if ($result['ret'] === false) {
            writelog("UC请求转化回传api失败1", 'callbackapi');
            return false;
        }
        writelog("表单id：{$form_id}，UC请求转化回传api,请求参数:".json_encode($params, JSON_UNESCAPED_UNICODE).",返回参数:".$result['msg'], 'callbackapi');
        if (empty($result['msg'])) {
            writelog("UC请求转化回传api失败2", 'callbackapi');
            return false;
        }
        $result_array = json_decode($result['msg'], true);
        if ($result_array['status'] != 0) {
            writelog("UC请求转化回传api失败3", 'callbackapi');
            return false;
        }

        return true;
    }

    /**
     * 腾讯转化回传api对接
     * @params int $form_id 表单id
     * @params int $url 前端页面完整url
     * @params string $click_id 点击id
     * @return boolean
     */
    public function tengxunCallbackApi($form_id, $form_url, $click_id)
    {
        $url = "http://tracking.e.qq.com/conv/web";

        $url_info = parse_url($form_url);
        $params = [
            'link' => urlencode($url_info['host']),
            'clickid' => $click_id, // 点击id 唯一标识
            "action_time" => time(), // 秒
            'action_type' => "RESERVATION",
        ];
        $result = Http::sendRequest($url, $params,'GET');
        if ($result['ret'] === false) {
            writelog("腾讯请求转化回传api失败1", 'callbackapi');
            return false;
        }
        writelog("表单id：{$form_id}，腾讯请求转化回传api,请求参数:".json_encode($params, JSON_UNESCAPED_UNICODE).",返回参数:".$result['msg'], 'callbackapi');
        if (empty($result['msg'])) {
            writelog("腾讯请求转化回传api失败2", 'callbackapi');
            return false;
        }
        $result_array = json_decode($result['msg'], true);
        if ($result_array['code'] != 0) {
            writelog("腾讯请求转化回传api失败3", 'callbackapi');
            return false;
        }

        return true;
    }


    /**
     * post发送json格式的数据
     */
    public function postJson($url, $data)
    {

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            throw new ParamException(['msg' => '请求数据不能为空', 'errorCode' => 10000]);
        }

        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);

        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }


    public function success($message = "ok", $data = [])
    {
        return json(['code' => 0, 'message' => $message, 'data' => $data]);
    }

    public function error($message = "error", $data = [])
    {
        return json(['code' => 500, 'message' => $message, 'data' => $data]);
    }
}